package com.example.guiguiapplicatio.fragment.FamilySigning;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.FamilyarChivesRecordList;
import com.example.guiguiapplicatio.Response.FamilyarChooseService;
import com.example.guiguiapplicatio.Response.FamilyarSigning;
import com.example.guiguiapplicatio.Response.Record;
import com.example.guiguiapplicatio.fragment.FamilyArchives.adapter.FamilyArchivesAdapter;
import com.example.guiguiapplicatio.fragment.FamilySigning.adapter.FamilySigningAdapter;
import com.example.guiguiapplicatio.fragment.FamilySigning.adapter.OnServicePackageSelectedListener;
import com.example.guiguiapplicatio.fragment.FamilySigning.adapter.OnServicePackageSelectedListener2;
import com.example.guiguiapplicatio.fragment.home.HealthRecordFragment;

import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.ApiUtils;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;


import cn.refactor.lib.colordialog.PromptDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FamilySigningFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    TextView et_ethnic;
    TextView et_phone;
    TextView et_detailedresidence;
    TextView et_Profession;
    TextView et_marriage;
    TextView tv_reason;
    TextView tv_finish;
    ImageButton servic_back;
    RecyclerView recyclerView;
    RadioGroup radio_group_surgery;
    RadioButton radbtn;
    Button comit_btu;
    // TODO: Rename and change types of parameters
    private String idCard;
    private ApiUtils apiUtils;
    private String intentHouseholdName;
    private int intentFamilyNum;
    private String intentHouseholdPhone;
    private String intentHouseholdAddress;
    private String intentStaTime;
    private String intentEndTime;
    private List<String> memberName = new ArrayList<>();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
    private FamilySigningAdapter familySigningAdapter;
    private OnServicePackageSelectedListener listener;
    private List<FamilyarChooseService> familyarchooseserviceList = new ArrayList<>();

    public FamilySigningFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HealthRecordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FamilySigningFragment newInstance(String param1, String param2) {
        FamilySigningFragment fragment = new FamilySigningFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString("idCard");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_total_detail_family_sign, container, false);
        servic_back = root.findViewById(R.id.servic_back);
        apiUtils = new ApiUtils(getString(R.string.api));
        et_ethnic = root.findViewById(R.id.et_ethnic);
        et_phone = root.findViewById(R.id.et_phone);
        et_detailedresidence = root.findViewById(R.id.et_detailedresidence);
        et_Profession = root.findViewById(R.id.et_Profession);
        et_marriage = root.findViewById(R.id.et_marriage);
        tv_reason = root.findViewById(R.id.tv_reason);
        tv_finish = root.findViewById(R.id.tv_finish);
        recyclerView = root.findViewById(R.id.examination_start_list);
        radio_group_surgery = (RadioGroup) root.findViewById(R.id.radio_group_surgery);
        comit_btu = root.findViewById(R.id.comit_btu);
        Call<ResponseBody<FamilyarSigning>> FamilyarSigningCall = apiUtils.getApi().getFamilyarChivesSigningList(idCard, PreferencesUtil.getInt(getContext(), "doctor_id"));
        FamilyarSigningCall.clone().enqueue(new Callback<ResponseBody<FamilyarSigning>>() {
            @Override
            public void onResponse(Call<ResponseBody<FamilyarSigning>> call, Response<ResponseBody<FamilyarSigning>> response) {
                ResponseBody<FamilyarSigning> responseBody = response.body();
                if (responseBody != null && responseBody.getData() != null) {
                    FamilyarSigning familyarSigning = responseBody.getData();
                    et_ethnic.setText(familyarSigning.getHouseholdName());
                    et_phone.setText(familyarSigning.getHouseholdPhone());
                    et_detailedresidence.setText(familyarSigning.getHomeAddress());
                    et_Profession.setText(familyarSigning.getOrganization());
                    et_marriage.setText(familyarSigning.getDoctorName());
                    LinearLayoutManager manager = new LinearLayoutManager(getContext());
                    recyclerView.setLayoutManager(manager);
                    familySigningAdapter = new FamilySigningAdapter(familyarSigning.getFamilyMembers(), getContext(), apiUtils.getApi(), new OnServicePackageSelectedListener2() {
                        @Override
                        public void onServicePackagesSelected(List<FamilyarChooseService> familyarChooseServiceList) {
                            familyarchooseserviceList = familyarChooseServiceList;
                        }
                    });
                    recyclerView.setAdapter(familySigningAdapter);
                    intentHouseholdName = familyarSigning.getHouseholdName();
                    intentFamilyNum = familyarSigning.getFamilyMembers().size();
                    intentHouseholdPhone = familyarSigning.getHouseholdPhone();
                    intentHouseholdAddress = familyarSigning.getHomeAddress();
                    for (FamilyarChivesRecordList familyarChivesRecordList : familyarSigning.getFamilyMembers()) {
                        memberName.add(familyarChivesRecordList.getName());
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<FamilyarSigning>> call, Throwable t) {

            }
        });
        tv_reason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radio_group_surgery.check(R.id.radio_customize);
                new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(0, // 显示年
                                1, // 显示月
                                2)
                        .showBackNow(false)
                        .setTitle("选择时间")
                        .setOnChoose("确定", aLong -> {
                            Date selectedDate = new Date(aLong);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
                            String formattedDate = sdf.format(selectedDate);
                            tv_reason.setText(formattedDate);
                        }).build().show();
            }
        });
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radio_group_surgery.check(R.id.radio_customize);
                new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(0, // 显示年
                                1, // 显示月
                                2)
                        .showBackNow(false)
                        .setTitle("选择时间")
                        .setOnChoose("确定", aLong -> {
                            Date selectedDate = new Date(aLong);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
                            String formattedDate = sdf.format(selectedDate);
                            tv_finish.setText(formattedDate);
                        }).build().show();
            }
        });
        radio_group_surgery.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radbtn = (RadioButton) root.findViewById(radio_group_surgery.getCheckedRadioButtonId());
                if (radbtn.getText().equals("一年")) {
                    Calendar currentDate = Calendar.getInstance();
                    Calendar endDate = (Calendar) currentDate.clone();
                    endDate.add(Calendar.YEAR, 1); // 到明年的今天结束
                    String startDateString = dateFormat.format(currentDate.getTime());
                    String endDateString = dateFormat.format(endDate.getTime());
                    tv_reason.setText(startDateString);
                    tv_finish.setText(endDateString);
                }
                if (radbtn.getText().equals("本年")) {
                    Calendar currentDate = Calendar.getInstance();
                    // 获取本年的结束日期
                    Calendar endDate = Calendar.getInstance();
                    endDate.set(Calendar.MONTH, 11); // 设置为12月（11表示12月，因为月份从0开始）
                    endDate.set(Calendar.DAY_OF_MONTH, 31); // 设置为本年的最后一天
                    // 格式化日期为字符串
                    String startDateString = dateFormat.format(currentDate.getTime());
                    String endDateString = dateFormat.format(endDate.getTime());
                    tv_reason.setText(startDateString);
                    tv_finish.setText(endDateString);
                }
            }
        });
        servic_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_FamilySigningFragment_to_FamilyArchivesFragment, bundle);
            }
        });
        comit_btu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FamilySigingNextActivity.class);
                intentStaTime = tv_reason.getText().toString();
                intentEndTime = tv_finish.getText().toString();

                if(intentStaTime.equals("") || intentEndTime.equals("")){
                    new PromptDialog(getContext())
                            .setDialogType(PromptDialog.DIALOG_TYPE_INFO)
                            .setAnimationEnable(true)
                            .setTitleText("INFO")
                            .setContentText("请选择签约日期")
                            .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                @Override
                                public void onClick(PromptDialog dialog) {
                                    dialog.dismiss();
                                }
                            }).show();
                }
                else {
                    if(familyarchooseserviceList.size() != intentFamilyNum){
                        new PromptDialog(getContext())
                                .setDialogType(PromptDialog.DIALOG_TYPE_INFO)
                                .setAnimationEnable(true)
                                .setTitleText("INFO")
                                .setContentText("请为家庭成员选择服务包")
                                .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                    @Override
                                    public void onClick(PromptDialog dialog) {
                                        dialog.dismiss();
                                    }
                                }).show();
                    }
                    else {
                        String familyarchooseserviceListJson = new Gson().toJson(familyarchooseserviceList);
                        Call<ResponseBody<List<List<Record>>>> responseBodyCall = apiUtils.getApi().SearchFamilySigningAll(familyarchooseserviceListJson,intentStaTime,intentEndTime);
                        responseBodyCall.clone().enqueue(new Callback<ResponseBody<List<List<Record>>>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<List<List<Record>>>> call, Response<ResponseBody<List<List<Record>>>> response) {
                                ResponseBody<List<List<Record>>> responseBody = response.body();
                                if(responseBody != null && responseBody.getData() != null){
                                    List<List<Record>> recordList = responseBody.getData();
                                    List<String>  recordListName = new ArrayList<>();
                                    for (List<Record> recordlist : recordList){
                                        for (Record record : recordlist){
                                            recordListName.add(record.getName());
                                        }
                                    }
                                    new PromptDialog(getContext())
                                            .setDialogType(PromptDialog.DIALOG_TYPE_WRONG)
                                            .setAnimationEnable(true)
                                            .setTitleText("WRONG")
                                            .setContentText(recordListName + "已签约，请先解约")
                                            .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                                @Override
                                                public void onClick(PromptDialog dialog) {
                                                    dialog.dismiss();
                                                }
                                            }).show();
                                }
                                else {
                                    String familyarchooseserviceListJson = new Gson().toJson(familyarchooseserviceList);
                                    intent.putExtra("familyarchooseserviceList", familyarchooseserviceListJson);
                                    intent.putExtra("intentHouseholdName", intentHouseholdName);
                                    intent.putExtra("intentFamilyNum", intentFamilyNum);
                                    intent.putExtra("intentHouseholdPhone", intentHouseholdPhone);
                                    intent.putExtra("intentHouseholdAddress", intentHouseholdAddress);
                                    intent.putExtra("intentStaTime", intentStaTime);
                                    intent.putExtra("intentEndTime", intentEndTime);
                                    intent.putExtra("memberName", memberName.toString());
                                    startActivity(intent);
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<List<List<Record>>>> call, Throwable t) {

                            }
                        });
                    }
                }
            }
        });
        return root;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }
}
